/**
 * 获取右上菜单权限
 * @param {*} treeMenuData 菜单树数据
 * @param {*} defaultMenu 右上角预设菜单
 */
const findRightTopMenu = (treeDatas, defaultMenus) => {
    for (let treeItem of treeDatas) {
        for (let menuItem of defaultMenus) {
            if (menuItem.path == treeItem.url) {
                menuItem.isAuthorized = true;
            }
        }

        if (treeItem.children && treeItem.children.length > 0) {
            findRightTopMenu(treeItem.children, defaultMenus);
        }
    }
};

/**
 * 根据路由path找到对应的菜单项
 * @param {*} menuTrees 菜单集合
 * @param {*} path 路由路径
 */
const findMenuByPath = (menuTrees, path) => {
    let findedMenu = null;
    for (let treeItem of menuTrees) {
        if (treeItem.url == path) {
            findedMenu = treeItem;
            return findedMenu;
        }
        if (treeItem.children != null && treeItem.children.length > 0) {
            findedMenu = findMenuByPath(treeItem.children, path);
            if (findedMenu != null) return findedMenu;
        }
    }
    return findedMenu;
};

/**
 * 根据Key值找到对应的菜单项
 * @param {*} menuTrees 菜单集合
 * @param {*} key Key值
 */
const findMenuByKey = (menuTrees, key) => {
    let findedMenu = null;
    for (let treeItem of menuTrees) {
        if (treeItem.key == key) {
            findedMenu = treeItem;
            return findedMenu;
        }

        if (treeItem.children != null && treeItem.children.length > 0) {
            findedMenu = findMenuByKey(treeItem.children, key);
            if (findedMenu != null) return findedMenu;
        }
    }
    return findedMenu;
};

/**
 * 根据父级key值获取所有父级
 * @param {*} menuTrees 菜单集合
 * @param {*} parentKey 父级Key值
 */
const findMenuByParent = (menuTrees, parentKey, parentKeys) => {
    let parentMenu = findMenuByKey(menuTrees, parentKey);
    if (parentMenu != null) {
        parentKeys.push(parentMenu.key);
        if (parentMenu.parentId != "0") {
            findMenuByParent(menuTrees, parentMenu.parentId, parentKeys);
        }
    }
};

/**
 * 根据路由来定位左侧导航菜单，用于在其它位置点击菜单的同时左侧导航能同时展开定位
 * @param {*} menuTrees
 * @param {*} routePath
 */
const findNavToOpenKeys = (menuTrees, routePath) => {
    //从菜单中树种找到对应的导航菜单
    if (menuTrees == null || menuTrees.length == 0) {
        return null;
    }
    let findedMenu = findMenuByPath(menuTrees, routePath);
    //如果找到，根据此菜单向上寻找父级并放入数组集合

    let parentKeys = [];
    if (findedMenu != null) findMenuByParent(menuTrees, findedMenu.parentId, parentKeys);
    return {
        selectedKeys: findedMenu.key,
        openedKeys: parentKeys,
    };
};
export default { findRightTopMenu, findMenuByPath, findMenuByKey, findMenuByParent, findNavToOpenKeys };
